package com.haiqiu.backup;

import javax.swing.filechooser.FileSystemView;
import java.io.*;

/**
 * @author haiqiu
 * 创建定时备份sql脚本
 */
public class BackupSql {

    /**
     * 数据库
     */
    private final static String[] DATABASES = {
            "haiqiu_admin",
    };

    /**
     * cron表达式,每天凌晨3点备份数据库
     */
    private static final String CRON = "0 3 * * *";

    /**
     * 备份文件存放路径
     */
    private static final String BACKUP_DIR = "/root/esusong/mysqlbackup/";

    public static void main(String[] args) throws IOException {
        //当前用户桌面
        File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
        String desktopPath = desktopDir.getAbsolutePath();
        //判断cronTab是否存在，存在就删除重新追加
        //追加文件定时任务
        String cornTab = desktopPath + "\\数据库备份脚本文件\\cron脚本.txt";
        //操作说明
        String operation = desktopPath + "\\数据库备份脚本文件\\操作文档.txt";
        File fileCron = new File(cornTab);
        if (fileCron.exists()) {
            fileCron.delete();
            System.out.println("已删除存在的cron脚本文件");
        }
        File fileOperation = new File(cornTab);
        if (fileOperation.exists()) {
            fileOperation.delete();
            System.out.println("已删除存在的操作文档");
        }
        for (int i = 0; i < DATABASES.length; i++) {
            String sh = "\n" +
                    "#!/bin/sh\n" +
                    "#################################################\n" +
                    "# 备份数据库\n" +
                    "#################################################\n" +
                    "#mysqldump备份程序执行路径\n" +
                    "DUMP=/usr/bin/mysqldump\n" +
                    "#备份文件存放路径\n" +
                    "OUT_DIR=" + BACKUP_DIR + DATABASES[i] + "\n" +
                    "#备份文件所属权限\n" +
                    "LINUX_USER=root\n" +
                    "#要备份的数据库名字\n" +
                    "DB_NAME=" + DATABASES[i] + "\n" +
                    "#备份的天数,之前的删除\n" +
                    "DAYS=180\n" +
                    "\n" +
                    "# 如果文件夹不存在则创建\n" +
                    "\n" +
                    "if [ ! -d $OUT_DIR ];\n" +
                    "\n" +
                    "then\n" +
                    "\n" +
                    "mkdir -p $OUT_DIR;\n" +
                    "\n" +
                    "fi\n" +
                    "\n" +
                    "\n" +
                    "#进入备份存放目录\n" +
                    "cd $OUT_DIR\n" +
                    "#获取当前系统时间\n" +
                    "DATE=`date +%Y-%m-%d_%H:%M:%S`\n" +
                    "#备份数据库的文件名\n" +
                    "OUT_SQL=$DB_NAME\"_$DATE.sql\"\n" +
                    "#最终保存的数据库备份文件名\n" +
                    "TAR_SQL=$DB_NAME\"_$DATE.tar.gz\"\n" +
                    "#开始执行备份数据库\n" +
                    "$DUMP $DB_NAME > $OUT_DIR/$OUT_SQL\n" +
                    "\n" +
                    "#压缩为.tar.gz格式\n" +
                    "tar -czf $TAR_SQL ./$OUT_SQL --force-local\n" +
                    "#删除.sql格式的备份文件\n" +
                    "#rm $OUT_SQL\n" +
                    "#更改备份数据库文件的所有者\n" +
                    "chown $LINUX_USER:$LINUX_USER $OUT_DIR/$TAR_SQL\n" +
                    "#删除30天前的备份文件(注意:{} \\;中间有空格)\n" +
                    "find $OUT_DIR -name \"*.tar.gz\" -type f -mtime +$DAYS -exec rm -f {} \\;\n";

            //判断文件夹不存在就创建
            File file = new File(desktopPath + "\\数据库备份脚本文件\\");
            if (!file.exists()) {
                file.mkdir();
                System.out.println("目录文件夹不存在，已重新创建");
            }
            String filePath = desktopPath + "\\数据库备份脚本文件\\" + DATABASES[i] + "_bak.sh";
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(sh.getBytes());
            fos.close();

            System.out.println("脚本" + DATABASES[i] + "_bak.sh构建成功！");

            try {
                // 打开一个随机访问文件流，按读写方式
                RandomAccessFile randomFile = new RandomAccessFile(cornTab, "rw");
                // 文件长度，字节数
                long fileLength = randomFile.length();
                // 将写文件指针移到文件尾。
                randomFile.seek(fileLength);
                randomFile.writeBytes(CRON + "  /bin/sh " + BACKUP_DIR + DATABASES[i] + "_bak.sh" + "\r\n");
                randomFile.close();
                System.out.println("追加cron脚本内容成功！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //操作文档
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("1.登录服务器终端，输入命令：vi /etc/my.cnf\n")
                .append("底部追加字段\n")
                .append("[mysqldump]\n" +
                        "user=你的mysql用户名\n" +
                        "password=你的mysql密码\n")
                .append("2.输入命令创建文件夹：cd ~ && mkdir -p " + BACKUP_DIR + "\n")
                .append("3.复制生成的所有脚本到" + BACKUP_DIR + "目录下\n")
                .append("4.输入命令：crontab -e\n")
                .append("复制cron脚本.txt里的内容到里面保存\n")
                .append("5.输入命令：systemctl restart crond\n");

        FileOutputStream fos = new FileOutputStream(operation);
        fos.write(stringBuffer.toString().getBytes());
        fos.close();

        System.out.println("数据库定时备份脚本生成完成！");
    }
}
